#!/usr/bin/env perl
use Mojolicious::Lite;
use GRBL;

my $grbl = GRBL->new();
my $templateVars = {};

# Simple html response
get '/' => sub {
   my $self = shift;


   # Check all Devices
   $templateVars->{devices} = [ map { ($_) = $_ =~ /dev\/(.+)/ } split(/,\s+/,`ls -m /dev/ttyUSB*`) ];

   # All NC Files
   $templateVars->{gfiles} = [ map { chomp $_; ($_) = $_ =~ /tmp\/(.+)/ } split(/,\s+/,`ls -m /tmp/*.nc`) ];

   $self->stash($templateVars);
   return $self->render('main');
};

# GRBL - connect device (?device=ttyUSB0&baudrate=9600)
get '/grbl/connect/:device/:baudrate' => sub {
   my $self    = shift;
   my $device = $self->param('device');
   my $baudrate = $self->param('baudrate');

   my $erg = $grbl->connect(sprintf('/dev/%s', $device), $baudrate);

   return $self->render_json({result => $erg})
};

# GRBL - close device
get '/grbl/close' => sub {
   my $self    = shift;

   my $erg = $grbl->close();

   return $self->render_json({result => $erg})
};

# GRBL - test device
get '/grbl/connected' => sub {
   my $self    = shift;

   my $erg = $grbl->connected();

   return $self->render_json({result => $erg})
};

# GRBL - send command
get '/grbl/command/:commands' => sub {
   my $self    = shift;
   my $commands = $self->param('commands');

   $commands =~ s/__/\./sig;

   my $erg = $grbl->cmd($commands);

   return $self->render_json({result => $erg})
};

# Multipart upload handler for GRBL Files
post '/upload' => sub {
   my $self = shift;

   # Check file size
   return $self->render(text => 'File is too big.', status => 200)
   if $self->req->is_limit_exceeded;

   # Process uploaded file
   return $self->redirect_to('form')
   unless my $grblfile = $self->param('grblfile');
   my $size = $grblfile->size;
   my $name = $grblfile->filename;

   # Save file in /tmp
   $grblfile->move_to("/tmp/$name");

   # return $self->render_json({result => "Thanks for uploading $size byte file $name."});
   return $self->redirect_to('/');
};


# GRBL - get splitted Content from File
get '/getFile/:filename' => sub {
   my $self    = shift;
   my $file    = '/tmp/' . $self->param('filename');

   $file =~ s/__/\./sig;

   die "Can't find file: $file or is empty!"
   if(! -s $file);

   my $content = [ map { $_ =~ s/\r+//sig; $_; } split(/\n/,`cat $file`) ];

   return $self->render_json($content);
};

# GRBL - get splitted Content from File
get '/grbl/info' => sub {
   my $self    = shift;

   my $erg = {};

   if($grbl->connected()){
      $erg = $grbl->cmd('?');
   
      foreach my $line (@$erg){
         my ($data) = $line =~ /\<(.+)\>/si;
         next unless($data);
         my @t = split(/[\,|\:]/, $data);
      
         $erg = {
            state => $t[0],
            machinepos => [$t[2],$t[3],$t[4]],
            workpos => [$t[6],$t[7],$t[8]],
         };
      }
   }


   return $self->render_json({result => $erg})
};


app->start;
